package com.zhima.jobhandler;

import com.lizhi.dto.CompleteResult;
import com.lizhi.entity.LocalTask;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zhima.entity.OjQuestionAudit;
import com.zhima.entity.OjQuestionPublish;
import com.zhima.enums.QuestionAuditState;
import com.zhima.feignclient.LocalTaskFeignClient;
import com.zhima.service.OjQuestionAuditService;
import com.zhima.service.OjQuestionPublishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.zhima.constant.QuestionXxlJobConstant.*;

@Slf4j
@Component
public class QuestionJobHandler {
    @Autowired
    private LocalTaskFeignClient localTaskFeignClient;
    @Autowired
    private OjQuestionAuditService ojQuestionAuditService;
    @Autowired
    private OjQuestionPublishService ojQuestionPublishService;

    @XxlJob("publish-question-handler")
    public void publishQuestionHandler() {
        // 1、审核表的内容复制到发布表
        // 2、将内容更新到Redis中
        // 3、将内容更新到ES中
        int shardTotal = XxlJobHelper.getShardTotal();
        int shardIndex = XxlJobHelper.getShardIndex();
        List<LocalTask> localTasks = localTaskFeignClient.dispatchTasksBasedOnShared(shardTotal, shardIndex, PUBLISH_QUESTION, TASK_LIMIT);
        // 发布题目
        log.info("获取发布题目的任务{}条", localTasks.size());
        // 题目内容都合法
        for (LocalTask localTask : localTasks) {
            // 下一个要处理的任务
            int nextSubTaskIndex = localTask.getNextSubTaskIndex();
            // 题目id
            long questionId = Long.parseLong(localTask.getBusinessKeys().get(0));
            // 防止同一个任务多次查询数据库
            OjQuestionPublish ojQuestionPublish = null;
            while (nextSubTaskIndex < 3) {
                try {
                    localTaskFeignClient.startSubTaskWithoutSubTaskIndex(localTask.getId());
                    if (nextSubTaskIndex == 0) {
                        // MySQL->0
                        // 将审核表的这道题的信息复制到发布表
                        // 将审核表的题目复制到发布表
                        ojQuestionPublish = ojQuestionPublishService.publishQuestionAudit(questionId);
                    } else if (nextSubTaskIndex == 1) {
                        // Redis->1
                        ojQuestionPublish = ojQuestionPublishService.publishQuestionToRedis(ojQuestionPublish, questionId);
                    } else if (nextSubTaskIndex == 2) {
                        // Es->2
                        ojQuestionPublishService.publishQuestionToEs(ojQuestionPublish, questionId);
                        // 发布成功后就将审核箱中的题目删除
                        ojQuestionAuditService.cancelSubmitQuestionAudit(questionId);
                    }
                    // 标记完成子任务
                    localTaskFeignClient.completeSubTaskWithSubTaskIndex(localTask.getId(), new CompleteResult(nextSubTaskIndex));
                    nextSubTaskIndex++;
                } catch (Exception e) {
                    // 通知失败
                    e.printStackTrace();
                    localTaskFeignClient.completeSubTaskWithSubTaskIndex(localTask.getId(), new CompleteResult(e.getMessage()));
                }
            }
        }
    }

    @XxlJob("audit-question-handler")
    public void auditQuestionHandler() {
        // 1、审核草稿表中的内容
        int shardTotal = XxlJobHelper.getShardTotal();
        int shardIndex = XxlJobHelper.getShardIndex();
        List<LocalTask> localTasks = localTaskFeignClient.dispatchTasksBasedOnShared(shardTotal, shardIndex, AUDIT_QUESTION, TASK_LIMIT);
        // 审核题目
        log.info("获取审核题目的任务{}条", localTasks.size());
        for (LocalTask localTask : localTasks) {
            try {
                localTaskFeignClient.startSubTaskWithoutSubTaskIndex(localTask.getId());
                long questionAuditId = Long.parseLong(localTask.getBusinessKeys().get(0));
                // 标记开始子任务
                OjQuestionAudit questionAudit = ojQuestionAuditService.getById(questionAuditId);
                // 输入输出案例不得为空
                if (questionAudit.getInOutExamples() == null || questionAudit.getInOutExamples().isEmpty()) {
                    ojQuestionAuditService.updateAuditState(questionAuditId, QuestionAuditState.NOT_PASS_AUDIT);
                }
                // TODO 检查题目名称、题目背景、题目描述、输入格式、输出格式、题目提示不得有敏感词
                // TODO 批量处理审核结果
                // 审核通过
                ojQuestionAuditService.updateAuditState(questionAuditId, QuestionAuditState.PASS_AUDIT);
                // 标记完成子任务
                localTaskFeignClient.completeSubTaskWithSubTaskIndex(localTask.getId(), new CompleteResult());
            } catch (Exception e) {
                e.printStackTrace();
                localTaskFeignClient.completeSubTaskWithSubTaskIndex(localTask.getId(), new CompleteResult(e.getMessage()));
            }
        }
    }

    @XxlJob("delete-question-handler")
    public void deleteQuestionHandler() {
        // TODO 删除题目
        // 1、将Redis中的数据删除
        // 2、将ES中的题目数据删除
    }
}
